package com.schedule.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.schedule.Util.PagedGridResult;
import com.schedule.pojo.*;
import com.schedule.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author star
 * @since 2022-02-12
 */
@Api(tags = "AdminController")
@RestController
public class AdminController {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAdminRoleService adminRoleService;




    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode()
                ,request);
    }

    @ApiOperation(value="获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public RespBean getAdminInfo(Principal principal){//主体：使用系统的用户或设备或从其他系统远程登录的用户
        if (null==principal){
            return RespBean.error("没有查询到该用户") ;
        }
        String username = principal.getName();
        Admin admin=adminService.getAdminByUserName(username);
        admin.setPassword(null);//保护密码
        admin.setRoles(adminService.getRoles(admin.getId()));
        return RespBean.success("查询成功",admin);
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("注销成功！");
    }

    @ApiOperation(value="注册")
    @PostMapping("/register")
    public RespBean register(@RequestBody AdminRegisterParam adminRegisterParam){
        Admin admin = adminService.getAdminByUserName(adminRegisterParam.getUserName());
        if(null!=admin){
            return RespBean.error("用户名已存在！");
        }else{
            admin=adminService.getAdminByPhoneNum(adminRegisterParam.getPhoneNum());
            if(null!=admin){
                return RespBean.error("手机号已存在！");
            }
        }
        if (adminService.add(adminRegisterParam)){
            admin=adminService.getAdminByUserName(adminRegisterParam.getUserName());
            Role role = roleService.getRoleByName("运动员");
            AdminRole adminRole=new AdminRole();
            adminRole.setAdminId(admin.getId());
            adminRole.setRid(role.getId());
            adminRoleService.save(adminRole);
            return RespBean.success("注册成功！");
        }
        return RespBean.error("注册失败！");
    }

    @ApiOperation(value = "验证用户密码")
    @PostMapping("/verify")
    public RespBean verifyPassword(@RequestParam("password") String password){
        if(adminService.verifyPassword(password)){
            return RespBean.success("密码正确");
        }
        return RespBean.error("密码错误");
    }

    @ApiOperation(value = "修改用户密码")
    @PostMapping("/modify")
    @Transactional//事务
    public RespBean modifyUserInformation(@RequestParam("newPassword") String newPassword){
        Admin currentAdmin = adminService.getCurrentAdmin();
        String encode = passwordEncoder.encode(newPassword);
        boolean update = adminService.update(new UpdateWrapper<Admin>()
                .eq("id", currentAdmin.getId())
                .set("password", encode));
        if(update){
//            RespBean bean = adminServ ice.loginWithoutCode(currentAdmin.getUsername(), encode);
            return RespBean.success("修改成功");
        }
        return RespBean.error("修改失败");
    }

    @ApiOperation(value = "获取所有用户信息")
    @GetMapping("/authority/user/getAllAdmin")
    public RespBean getAllAdmin(@RequestParam(name="page") Integer page,
                                @RequestParam(name="pageSize") Integer pageSize){
        PageHelper.startPage(page, pageSize);
        List<Admin> admins = adminService.list();
        for (Admin admin : admins) {
            admin.setPassword(null);
            admin.setRoles(adminService.getRoles(admin.getId()));
        }
        PagedGridResult gridAdmins = PagedGridResult.setterPagedGrid(admins, page);
        return RespBean.success("获取成功",gridAdmins);
    }

    @ApiOperation(value = "管理员重置用户密码")
    @PostMapping("/authority/user/resetPassword")
    @Transactional//事务
    public RespBean resetAdminPassword(@RequestParam("Aid") Integer Aid,@RequestParam("newPassword") String newPassword){
        String encode = passwordEncoder.encode(newPassword);
        boolean update = adminService.update(new UpdateWrapper<Admin>()
                .eq("id", Aid)
                .set("password", encode));
        if(update){
            return RespBean.success("重置成功");
        }
        return RespBean.error("重置失败");
    }

    @ApiOperation(value = "查询用户")
    @GetMapping("/authority/user/queryAdmin")
    public RespBean queryAdmin(@RequestParam(name = "parameter") String parameter,
                               @RequestParam(name="page") Integer page,
                               @RequestParam(name="pageSize") Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<Admin> admins = adminService.fuzzyQueryAdminByUserName(parameter);
//        List<Admin> admins=adminService.fuzzyQueryAdminByPhoneNum(parameter);
        if(0!=admins.size()){
            for (Admin admin : admins) {
                admin.setPassword(null);
                admin.setRoles(adminService.getRoles(admin.getId()));
            }
            PagedGridResult gridAdmins=PagedGridResult.setterPagedGrid(admins,page);
            return RespBean.success("查找成功！",gridAdmins);
        }else{
            PageHelper.startPage(page,pageSize);
            admins=adminService.fuzzyQueryAdminByPhoneNum(parameter);
            if(0!=admins.size()){
                for (Admin admin : admins) {
                    admin.setPassword(null);
                    admin.setRoles(adminService.getRoles(admin.getId()));
                }
                PagedGridResult gridAdmins=PagedGridResult.setterPagedGrid(admins,page);
                return RespBean.success("查找成功！",gridAdmins);
            }
        }
//        for (Admin admin : admins) {
//            admin.setPassword(null);
//            admin.setRoles(adminService.getRoles(admin.getId()));
//        }
//        PagedGridResult gridAdmins=PagedGridResult.setterPagedGrid(admins,page);
//        return RespBean.success("查找成功！",gridAdmins);
        return RespBean.error("查找失败，用户不存在！");
    }
}
